package com.lee.study.shouji.engine;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;

/**
 * @description 下载APP
 *
 * @author AlexLee
 *
 * @Create 2013-5-29 下午2:44:28
 */
public class DownLoadFileTask{
	
	/**
	 * 下载文件并记录下载的字节树
	 * @param path
	 * @param filePath
	 * @param pd
	 * @return
	 * @throws IOException 
	 * @throws InterruptedException 
	 */
	public static File getFile(String path,String filePath,ProgressDialog pd) throws IOException, InterruptedException{

		URL url = new URL(path);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("GET");
		connection.setConnectTimeout(5000);
		//请求成功
		if(connection.getResponseCode() == 200){
			
			int total = connection.getContentLength();
			pd.setMax(total);
			
			InputStream is = connection.getInputStream();
			
			File file = new File(filePath);
			FileOutputStream fos = new FileOutputStream(file);
			
			byte[] buffer = new byte[1024];
			int len = 0;
			int process = 0;
			while((len = is.read(buffer)) != -1){
				fos.write(buffer,0,len);
				process += len;
				pd.setProgress(process);
				//为了充分展示下载的过程，循环一次暂停50毫秒
				Thread.sleep(50);
			}
			fos.flush();
			fos.close();
			
			return file;
		}
		
		return null;
	}

}
